package top.kaoshanji.q1ch05a.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import top.kaoshanji.q1ch05a.dao.SpittleRepository;
import top.kaoshanji.q1ch05a.model.Spittle;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * 写一遍就会了...但是如果一遍都不写，那么就不太可能会了..
 * @author kaoshanji
 * ^_^
 * create time 2025/4/24 10:56
 */
@Repository
public class JdbcSpittleRepository implements SpittleRepository {

    private JdbcOperations jdbc;

    @Autowired
    public void setJdbc(JdbcOperations jdbc) {
        this.jdbc = jdbc;
    }

    @Override
    public List<Spittle> findSpittles(long max, int count) {

        return jdbc.query(" select id, message, created_at, latitude, longitude " +
                        " from Spittle " +
                        " where id < ? " +
                        " order by created_at desc limit 20 ",
                new SpittleRowMapper(), max);
    }

    @Override
    public Spittle findOne(long id) {
        List<Spittle> spittles = jdbc.query(
                " select id, message, created_at, latitude, longitude " +
                        " from Spittle " +
                        " where id = ? ",
                new SpittleRowMapper(), id);
        return spittles.size() > 0 ? spittles.get(0) : null;
    }

    private static class SpittleRowMapper implements RowMapper<Spittle> {

        @Override
        public Spittle mapRow(ResultSet resultSet, int i) throws SQLException {
            return new Spittle(
                    resultSet.getLong("id"),
                    resultSet.getString("message"),
                    resultSet.getDate("created_at"),
                    resultSet.getDouble("longitude"),
                    resultSet.getDouble("latitude")
            );
        }
    }

}
